//
//  TodoItem.swift
//  memo
//
//  Created by fly on 2019/9/28.
//  Copyright © 2019 Xiang HongFei. All rights reserved.
//

import Foundation
import UserNotifications

class TodoItem: NSObject, NSCoding {
    func encode(with coder: NSCoder) {
        coder.encode(text, forKey: "Text")
        coder.encode(checked,forKey: "Checked")
        coder.encode(dueDate,forKey: "DueDate")
        coder.encode(shouldRemind,forKey: "ShouldRemind")
        coder.encode(repertory,forKey: "Repertory")
    }
    
    required init?(coder acoder: NSCoder) {
        text = acoder.decodeObject(forKey: "Text") as! String
        checked = acoder.decodeBool(forKey: "Checked")
        dueDate = acoder.decodeObject(forKey: "DueDate") as! Date
        shouldRemind = acoder.decodeBool(forKey: "ShouldRemind")
        repertory = acoder.decodeObject(forKey: "Repertory") as! String
        super.init()
    }
    
    var text = ""
    var checked = false
    
    var dueDate = Date()
    var shouldRemind = false
    
    var repertory = ""
    
    
    
    init(text: String,checked: Bool) {
        super.init()
    }
    
    func scheduleNotification(){
        if shouldRemind && dueDate > Date() {
            let content = UNMutableNotificationContent()
            content.title = "备忘录"
            content.body = text
            content.sound = UNNotificationSound.default
            
            let calender = Calendar(identifier: .gregorian)
            let component = calender.dateComponents([.month,.day,.hour,.minute], from: dueDate)
            
            let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: false)
            let request = UNNotificationRequest(identifier: text, content: content, trigger: trigger)
            let center = UNUserNotificationCenter.current()
            
            center.add(request)
        }
    }
    
    func removeNotification() {
        let center = UNUserNotificationCenter.current()
        center.removePendingNotificationRequests(withIdentifiers: [text])
        
    }
    
    deinit {
        removeNotification()
    }
}
